#undef UNICODE
#include "DrawListMessage.h"

#include <stdio.h>
#include <stdlib.h>

void DrawListMessage::CombineString(char* buffer, char* string1, char* string2)
{
	sprintf_s(buffer, MESSAGE_BUFF_LEN*5, "%s%s", string1, string2);
}

void DrawListMessage::pack(char* buffer)
{
	char temp[MESSAGE_BUFF_LEN] = "";

	for(int i=0;i<drawList.Size();++i)
	{
		DrawStruct dSt = drawList.get(i);
		int drawFromCenter = -1;
		if(dSt.DrawFromCenter)
			drawFromCenter = 1;
		//size scale
		//X#Y#X#Y#tex#rot#
		sprintf_s(temp, MESSAGE_BUFF_LEN, "D#%g#%g#%g#%g#%i#%g#%i#", dSt.pos.x, dSt.pos.y, dSt.scale.x, dSt.scale.y, dSt.Tex, dSt.orientation, drawFromCenter);
		CombineString(buffer, buffer, temp);
	}
	CombineString(buffer, buffer, "X#");
}

void DrawListMessage::unPack(char* dataBuffer)
{
	drawList.clear();
	
	char end = '\0', *p = &end;
	int counter=0;
	
	if(dataBuffer && dataBuffer != (char*)0xfefefefe)
	{
		//flag
		counter += ParseString(counter, temp, dataBuffer, stop);
		while(temp[0] != 'D' && temp[0] != 'X')
		{
			counter += ParseString(counter, temp, dataBuffer, stop);
			if(counter > MESSAGE_BUFF_LEN)
				return;
		}

		while(temp[0] == 'D')
		{
			DrawStruct dSt;

			//pos
			counter += ParseString(counter, temp, dataBuffer, stop);
			dSt.pos.x = (float)atof(temp);
			counter += ParseString(counter, temp, dataBuffer, stop);
			dSt.pos.y = (float)atof(temp);

			//scale
			counter += ParseString(counter, temp, dataBuffer, stop);
			dSt.scale.x = (float)atof(temp);
			counter += ParseString(counter, temp, dataBuffer, stop);
			dSt.scale.y = (float)atof(temp);

			//texture
			counter += ParseString(counter, temp, dataBuffer, stop);
			dSt.Tex = strtol(temp, &p, 10);

			//rotation
			counter += ParseString(counter, temp, dataBuffer, stop);
			dSt.orientation = (float)atof(temp);

			counter += ParseString(counter, temp, dataBuffer, stop);
			int drawFromCenter = atol(temp);
			dSt.DrawFromCenter = (drawFromCenter > 0);

			drawList.add(dSt);

			//flag
			counter += ParseString(counter, temp, dataBuffer, stop);
		}
	}
}

void DrawListMessage::setData(LostVector<DrawStruct>* dList)
{
	drawList.clear();
	for(int i=0;i<dList->Size();++i)
		drawList.add(dList->get(i));
}